package com.paas.form.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.paas.common.model.BaseUserInfo;
import com.paas.common.model.DataBaseEntity;
import com.paas.common.model.RestResponse;
import com.paas.common.util.BeanUtil;
import com.paas.common.util.StringUtil;
import com.paas.common.web.SystemConst;
import com.paas.common.web.annotion.OperLog;
import com.paas.common.web.controller.BaseController;
import com.paas.common.web.oper.OprLogConstant;
import com.paas.form.entity.FormModelEntity;
import com.paas.form.entity.FormModelParamsEntity;
import com.paas.form.service.IFormModelParamsService;
import com.paas.form.service.IFormModelService;
import com.paas.form.vo.RuleModelVo;
import com.publics.entity.UcUserEntity;
import com.publics.feign.service.IUcDataBaseService;
import com.publics.feign.service.IUcUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/form/formModel")
@Api(description = "规则模型", tags = "")
public class FormModelController extends BaseController {

    @Autowired
    public IFormModelService formModelService;

    @Autowired
    public IUcDataBaseService ucDataBaseService;

    @Autowired
    public IUcUserService ucUserService;

    @Autowired
    public IFormModelParamsService formModelParamsService;


    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(value = "保存信息", notes = "保存信息")
    @OperLog(operType = OprLogConstant.ADD, operModul = "", operDescribe = "-保存")
    public RestResponse save(@RequestBody RuleModelVo ruleModelVo) throws ParseException {
        BaseUserInfo baseUserInfo = getUserInfo();
        if (BeanUtil.isNotEmpty(ruleModelVo)) {
            FormModelEntity formModelEntity = ruleModelVo.getFormModelEntity();
            if (BeanUtil.isNotEmpty(formModelEntity)) {
                formModelEntity.setOrgId(baseUserInfo.getOrgId());
                formModelEntity.setAppId(baseUserInfo.getAppId());
                formModelEntity.setStatus(SystemConst.NORMAL_STATUS);
                formModelEntity.setModifyId(baseUserInfo.getUserId());
                formModelEntity.setModifyDate(new Date());
                injectUpdateDataAuth(formModelEntity);
                formModelService.save(formModelEntity);
                //
                if (StringUtil.isNotEmpty(formModelEntity.getId())) {
                    // 模型参数-删除
                    LambdaQueryWrapper<FormModelParamsEntity> paramsWrapper = new LambdaQueryWrapper<FormModelParamsEntity>();
                    paramsWrapper.eq(FormModelParamsEntity::getModelId, formModelEntity.getId());
                    formModelParamsService.remove(paramsWrapper);
                    //
                    List<FormModelParamsEntity> formModelParamsEntityList = ruleModelVo.getParamsList();
                    if (formModelParamsEntityList.size() > 0) {
                        for (FormModelParamsEntity formModelParam : formModelParamsEntityList) {
                            formModelParam.setModelId(formModelEntity.getId());
                            formModelParam.setStatus(SystemConst.NORMAL_STATUS);
                            formModelParam.setAppId(baseUserInfo.getAppId());
                            formModelParam.setModifyId(baseUserInfo.getUserId());
                            formModelParam.setModifyDate(new Date());
                        }
                        formModelParamsService.saveBatch(formModelParamsEntityList);
                    }
                }
            }
            return RestResponse.error();
        }
        return RestResponse.success();
    }

    @RequestMapping(value = "/saveBatch", method = RequestMethod.POST)
    @ApiOperation(value = "批量保存信息", notes = "批量保存信息")
    @OperLog(operType = OprLogConstant.UPDATE, operModul = "", operDescribe = "-批量保存修改")
    public void saveBatch(@RequestBody List map) throws ParseException {
        List list = BeanUtil.mapsToList(map, FormModelEntity.class);
        formModelService.saveBatch(list);
    }

    @RequestMapping(value = "/deleteById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id删除数据", notes = "根据Id删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-删除")
    public void delectById(String id) {
        if (null != id && !"".equals(id)) {
            FormModelEntity formModelEntity = new FormModelEntity();
            formModelEntity.setId(id);
            injectUpdateDataAuth(formModelEntity);
            formModelService.deleteByEntity(formModelEntity);
        }
    }

    @RequestMapping(value = "/queryByModelId", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id查询对象", notes = "根据Id查询对象")
    public RuleModelVo queryByModelId(String id) {
        RuleModelVo ruleModelVo = new RuleModelVo();
        if (StringUtil.isNotEmpty(id)) {
            FormModelEntity formModelEntity = formModelService.getById(id);
            if (BeanUtil.isNotEmpty(formModelEntity)) {
                DataBaseEntity dataBaseEntity = ucDataBaseService.queryById(formModelEntity.getDatabaseId());
                formModelEntity.setDatabaseName(dataBaseEntity.getJdbcName());
                ruleModelVo.setFormModelEntity(formModelEntity);
                FormModelParamsEntity formModelParamsEntity = new FormModelParamsEntity();
                formModelParamsEntity.setModelId(formModelEntity.getId());
                List<FormModelParamsEntity> list = formModelParamsService.getList(formModelParamsEntity);
                if (list.size() > 0) {
                    ruleModelVo.setParamsList(list);
                }
            }
        }
        return ruleModelVo;
    }

    @RequestMapping(value = "/deleteBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id批量删除数据", notes = "根据Id批量删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-批量删除")
    public void deleteBatchByIds(@RequestBody List ids) {
        formModelService.deleteBatchIds(ids);
    }

    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id查询对象", notes = "根据Id查询对象")
    public FormModelEntity queryById(String id) {
        FormModelEntity bean = formModelService.getById(id);
        return bean;
    }

    @RequestMapping(value = "/queryBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id查询对象列表", notes = "根据Id查询对象列表")
    public List queryBatchByIds(@RequestBody List ids) {
        List list = formModelService.getBatchByIds(ids);
        return list;
    }

    @RequestMapping(value = "/queryPage", method = RequestMethod.GET)
    @ApiOperation(value = "模板分页查询", notes = "模板分页查询")
    public IPage queryPage(FormModelEntity formModelEntity, Integer currentPage, Integer pageSize) {
        if (currentPage == null) {
            currentPage = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        formModelEntity.setAppId(getTokenModel().getAppId());
        injectUpdateDataAuth(formModelEntity);
        IPage<FormModelEntity> pageBean = formModelService.getPage(formModelEntity, currentPage, pageSize);
        List<FormModelEntity> list = pageBean.getRecords();
        if (BeanUtil.isNotEmpty(list) && list.size() > 0) {

            // 数据源id集合
            List<String> databaseIdList = list.stream().map(FormModelEntity::getDatabaseId).distinct().collect(Collectors.toList());
            // 数据源信息集合
            List<DataBaseEntity> databaseList = ucDataBaseService.queryByIds(databaseIdList);
            // 数据源信息集合-map
            Map<String, String> productMap = databaseList.stream().collect(Collectors.toMap(DataBaseEntity::getId, DataBaseEntity::getJdbcName));

            // 用户id集合
            List<String> idsList = list.stream().map(FormModelEntity::getCreateId).distinct().collect(Collectors.toList());
            // 用户信息集合
            List<UcUserEntity> userList = ucUserService.queryByIds(idsList);
            // 用户信息集合-map
            Map<String, String> userMap = userList.stream().collect(Collectors.toMap(UcUserEntity::getId, UcUserEntity::getUserName));

            // 设置-用户名称
            for (FormModelEntity ruleEntity : list) {
                ruleEntity.setDatabaseName(productMap.get(ruleEntity.getDatabaseId()));
                ruleEntity.setCreateName(userMap.get(ruleEntity.getCreateId()));
            }
        }
        return pageBean;
    }


    @RequestMapping(value = "/updateStatus", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id修改状态", notes = "根据Id修改状态")
    public RestResponse updateStatus(String id) {
        if (StringUtil.isNotEmpty(id)) {
            FormModelEntity formModelEntity = formModelService.getById(id);
            if (BeanUtil.isNotEmpty(formModelEntity)) {
                if ("1".equals(formModelEntity.getStatus())) {
                    formModelEntity.setStatus("2");
                } else {
                    formModelEntity.setStatus("1");
                }
            }
            formModelService.updateById(formModelEntity);
            injectUpdateDataAuth(formModelEntity);
            return RestResponse.success();
        }
        return RestResponse.error();
    }

}